package biz

import (
	"context"
	"fmt"
	"strings"

	"manage/api/user"
	"manage/internal/errors"
	"manage/internal/routes/common"
	"manage/internal/routes/model"
	"net/http"

	"github.com/Fromsko/gouitls/auth"
	"github.com/gin-gonic/gin"
)

func (u *APIUseCase) User() *Method {
	remoteName := "用户服务"
	remoteUser := u.Repo.User

	return &Method{
		Get: func(c *gin.Context) {
			userID := c.Param("user_id")
			role := c.Query("role")

			if role != "" {
				remoteUser(func(ctx context.Context, usc user.UserServiceClient) {
					reply, err := usc.GetUserList(ctx, &user.GetUserListRequest{Role: role})
					if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
						c.JSON(http.StatusOK, &errors.StandardResponse{
							Code: reply.Code,
							Msg:  reply.Msg,
							Data: reply.UserList,
						})
					}
				})
			} else {
				remoteUser(func(ctx context.Context, usc user.UserServiceClient) {
					reply, err := usc.GetUser(ctx, &user.GetUserRequest{UserId: userID})
					if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
						c.JSON(http.StatusOK, &errors.StandardResponse{
							Code: reply.Code,
							Msg:  reply.Msg,
							Data: reply.Data,
						})
					}
				})
			}
		},

		Post: func(c *gin.Context) {
			username := c.PostForm("username")
			password := c.PostForm("password")
			email := c.PostForm("email")
			role := c.DefaultPostForm("role", "学生")

			if username == "" || password == "" || email == "" {
				c.JSON(400, gin.H{"msg": "注册失败", "err": "参数不正确"})
				c.Abort()
				return
			}

			remoteUser(func(ctx context.Context, usc user.UserServiceClient) {
				reply, err := usc.AddUser(ctx, &user.AddUserRequest{
					Username: username,
					Password: password,
					Email:    email,
					Role:     role,
				})
				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
						Data: reply.Data,
					})
				}
			})
		},

		Put: func(ctx *gin.Context) {
			userID := ctx.Param("user_id")
			oldPasswd := ctx.PostForm("oldpwd")
			newPasswd := ctx.PostForm("newpwd")
			role := ctx.PostForm("role")

			remoteUser(func(c context.Context, usc user.UserServiceClient) {
				// 检查密码是否正确
				reply, _ := usc.GetUser(c, &user.GetUserRequest{UserId: userID})

				fmt.Println(reply.Data, reply.Code, reply.Msg)
				if reply.Code == 400 {
					// 用户不存在
					event := &common.JsonMsg{Ctx: ctx, Code: int(reply.Code)}
					if value := strings.Split(reply.Msg, ":"); len(value) != 0 {
						event.Msg = value[0]
						event.Err = &value[1]
					}
					common.OnSend(event)
					return
				} else {
					// 判断角色
					if v, _ := ctx.Get("role"); v != model.Admin.String() {
						// 非管理员 不能修改角色信息
						role = v.(string)
					}

					// 单独修改
					email := ctx.DefaultPostForm("email", reply.Data.Email)

					// 密码不正确
					if oldPasswd != "" && auth.HashString(oldPasswd) != reply.Data.Password {
						ctx.JSON(200, common.OnFailed(400, "更新失败", "密码不正确"))
						return
					}

					// 更新用户
					reply, err := usc.UpdateUser(c, &user.UpdateUserRequest{
						UserId:   userID,
						Username: reply.Data.Username,
						Password: newPasswd,
						Email:    email,
						Role:     role,
					})

					if errors.CheckErr(ctx, err, remoteName, reply.Code, reply.Msg) {
						ctx.JSON(http.StatusOK, &errors.StandardResponse{
							Code: reply.Code,
							Msg:  reply.Msg,
							Data: reply.Data,
						})
					}
				}
			})
		},

		Delete: func(c *gin.Context) {
			userID := c.Param("user_id")

			remoteUser(func(ctx context.Context, usc user.UserServiceClient) {
				reply, err := usc.DeleteUser(ctx, &user.DeleteUserRequest{UserId: userID})
				if errors.CheckErr(c, err, remoteName, reply.Code, reply.Msg) {
					c.JSON(http.StatusOK, &errors.StandardResponse{
						Code: reply.Code,
						Msg:  reply.Msg,
						Data: reply.Data,
					})
				}
			})
		},
	}
}
